package server.processors;

import java.nio.channels.ClosedChannelException;

import server.Client;
import server.NetworkMediator;
import server.ServerStateMediator;

import common.ChatPacket;
import common.Sendable;

public class ChatProcessor extends Processor {

	public ChatProcessor() {}
	
	public ChatProcessor(NetworkMediator mediator, ServerStateMediator server) {
		super( mediator, server );
	}
	
	@Override
	public Processor getInstanceOf(NetworkMediator mediator,
			ServerStateMediator server) {
		return new ChatProcessor( mediator, server);
	}

	@Override
	public boolean isInterestedIn(Sendable s) {
		return s instanceof ChatPacket;
	}

	public void run() {
		NetworkMediator network = getNetwork();
		
		ChatPacket chat = (ChatPacket) getServer().getMessage();
		
		if( !chat.isValid() )
			return;
		
		Client client = getServer().getClient();
		
		if( client.player != null && !client.player.getName().equals( chat.from ) )
			return;
		
		
		try {
			network.sendToAllClients( getServer().getMessage() );
		} catch (ClosedChannelException e) {
			e.printStackTrace();
		}
	}

}
